package com.itheima.springboottlias.service.impl;

import Pojo.Clazz;
import Pojo.ClazzQueryParam;
import Pojo.PageResult;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import com.itheima.springboottlias.anno.LogOperation;
import com.itheima.springboottlias.exception.NotAllowedException;
import com.itheima.springboottlias.mapper.ClazzMapper;
import com.itheima.springboottlias.mapper.StudentMapper;
import com.itheima.springboottlias.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

import static java.time.LocalDate.now;

@Service
public class ClazzServiceImpl implements ClazzService {
    @Autowired
    private ClazzMapper clazzMapper;
    @Autowired
    private StudentMapper studentMapper;

    // 添加班级
    @LogOperation
    @Override
    public void addClass(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.addClass(clazz);
    }
    // 查询所有班级
    @Override
    public List<Clazz> queryAll() {
        List<Clazz> clazzes = clazzMapper.queryAll();
        return clazzes;
    }
    // 分页和条件查询班级
    @Override
    public PageResult queryByCondition(ClazzQueryParam clazzQueryParam) {
        PageHelper.startPage(clazzQueryParam.getPage(),clazzQueryParam.getPageSize());
        Page<Clazz> page = (Page<Clazz>) clazzMapper.selectByCondition(clazzQueryParam);
        for (Clazz clazz : page) {
            if (clazz.getBeginDate().isAfter(now())){
                clazz.setStatus("未开课");
            }
            if (clazz.getEndDate().isBefore(now())){
                clazz.setStatus("已结课");
            }
            if (clazz.getBeginDate().isBefore(now())&&clazz.getEndDate().isAfter(now())){
                clazz.setStatus("在读");
            }
        }
        PageResult pageResult = new PageResult(page.getTotal(), page.getResult());
        return pageResult;
    }
    // 根据id删除班级
    @LogOperation
    @Override
    public void removeById(Integer id) {
        //0.删除之前，先查询出要删除的班级是否有学员
        //1.如果班级有学员，则不允许删除
        if (studentMapper.query(id) != 0) {
            //班级有学员，不允许删除
            throw new NotAllowedException("班级有学员，不允许删除");
        }
        clazzMapper.removeById(id);
    }
    // 根据id查询班级
    @LogOperation
    @Override
    public Clazz findById(Integer id) {
        return clazzMapper.findById(id);
    }
    // 修改班级
    @LogOperation
    @Override
    public void updateClass(Clazz clazz) {
        clazzMapper.updateClass(clazz);
    }


}
